package heven.holt.wan.android.repository

import androidx.paging.Pager
import androidx.paging.PagingConfig
import heven.holt.library.cache.CacheDoubleUtils
import heven.holt.wan.android.api.ApiWanUserServer
import heven.holt.wan.android.model.BaseModel
import heven.holt.wan.android.model.UserModel
import heven.holt.wan.android.paging.source.UserCoinRecordPagingSource

class WanUserRepository constructor(
    private val apiWanUserServer: ApiWanUserServer
) {
    companion object {
        private const val USER_INFO = "userInfo"
        private const val PAGE_SIZE = 20
    }

    /**
     * 登录
     */
    suspend fun login(username: String, password: String): BaseModel<UserModel> {
        return apiWanUserServer.login(username, password)
    }

    /**
     * 保存用户信息
     */
    fun saveUserInfo(userModel: UserModel) {
        CacheDoubleUtils.put(USER_INFO, userModel)
    }

    /**
     * 获取用户信息
     */
    fun getUserInfo(): UserModel? {
        return CacheDoubleUtils.getParcelable(USER_INFO, UserModel)
    }

    /**
     * 是否登录
     */
    fun isLogin(): Boolean = getUserInfo() != null

    /**
     * 获取用户积分
     */
    suspend fun getUserCoinInfo() = apiWanUserServer.getUserCoinInfo()

    /**
     * 获取个人积分获取列表
     */
    fun getUserCoinRecordListFlow() = Pager(
        config = PagingConfig(
            initialLoadSize = 10,
            prefetchDistance = 5,
            enablePlaceholders = false,
            pageSize = PAGE_SIZE
        )
    ) {
        UserCoinRecordPagingSource(apiWanUserServer)
    }.flow
}